import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import { chatApi } from '../api/chat'

export const useChatStore = defineStore('chat', () => {
  // 状态
  const messages = ref([])
  const isLoading = ref(false)
  const currentSessionId = ref(null)
  const error = ref(null)

  // 计算属性
  const hasMessages = computed(() => messages.value.length > 0)
  
  // 初始化会话ID
  const initSession = () => {
    if (!currentSessionId.value) {
      currentSessionId.value = uuidv4()
    }
  }

  // 添加消息
  const addMessage = (content, role = 'user', metadata = null) => {
    const message = {
      id: uuidv4(),
      content,
      role,
      timestamp: new Date().toISOString(),
      metadata,
      // 新增字段用于流式内容
      thinkingContent: '',
      actualContent: '',
      isStreaming: false
    }
    messages.value.push(message)
    return message
  }

  // 更新消息内容
  const updateMessage = (messageId, updates) => {
    const messageIndex = messages.value.findIndex(msg => msg.id === messageId)
    if (messageIndex > -1) {
      messages.value[messageIndex] = {
        ...messages.value[messageIndex],
        ...updates
      }
    }
  }

  // 发送消息
  const sendMessage = async (content, callbacks = {}) => {
    if (!content.trim()) return

    // 确保有会话ID
    initSession()
    
    // 添加用户消息
    addMessage(content, 'user')
    
    // 添加助手消息占位符
    const assistantMessage = addMessage('', 'assistant')
    assistantMessage.isStreaming = true
    
    isLoading.value = true
    error.value = null

    try {
      // 调用流式聊天API
      await chatApi.streamChat(
        content, 
        currentSessionId.value, 
        // onChunk 回调
        (chunk) => {
          if (chunk.type === 'data') {
            // 更新消息内容
            updateMessage(assistantMessage.id, {
              content: chunk.accumulatedContent,
              thinkingContent: chunk.thinkingContent,
              actualContent: chunk.actualContent,
              metadata: chunk.metadata,
              isStreaming: !chunk.isComplete
            })
            
            // 调用外部回调
            if (callbacks.onChunk) {
              callbacks.onChunk(chunk)
            }
          }
        },
        // onComplete 回调
        (finalData) => {
          updateMessage(assistantMessage.id, {
            content: finalData.content,
            thinkingContent: finalData.thinkingContent,
            actualContent: finalData.actualContent,
            metadata: finalData.metadata,
            isStreaming: false
          })
          isLoading.value = false
          
          // 调用外部回调
          if (callbacks.onComplete) {
            callbacks.onComplete(finalData)
          }
        }
      )
    } catch (err) {
      error.value = err.message || '发送消息失败'
      console.error('Chat error:', err)
      
      // 调用错误回调
      if (callbacks.onError) {
        callbacks.onError(err)
      }
      
      // 移除失败的助手消息
      const index = messages.value.findIndex(msg => msg.id === assistantMessage.id)
      if (index > -1) {
        messages.value.splice(index, 1)
      }
      isLoading.value = false
    }
  }

  // 清空聊天
  const clearChat = () => {
    messages.value = []
    currentSessionId.value = null
    error.value = null
  }

  // 加载历史消息
  const loadHistory = async (sessionId) => {
    if (!sessionId) return

    try {
      const history = await chatApi.getHistory(sessionId)
      if (history && history.msg && history.msg.messages) {
        messages.value = history.msg.messages.map(msg => ({
          id: uuidv4(),
          content: msg.content,
          role: msg.role,
          timestamp: new Date().toISOString(),
          metadata: null,
          thinkingContent: '',
          actualContent: msg.content,
          isStreaming: false
        }))
      }
      currentSessionId.value = sessionId
    } catch (err) {
      console.error('Load history error:', err)
      error.value = '加载历史消息失败'
    }
  }

  // 重新发送消息
  const resendMessage = async (messageIndex) => {
    if (messageIndex < 0 || messageIndex >= messages.value.length) return
    
    const message = messages.value[messageIndex]
    if (message.role !== 'user') return
    
    // 删除该消息及其后面的所有消息
    messages.value.splice(messageIndex)
    
    // 重新发送
    await sendMessage(message.content)
  }

  // 停止当前流式响应
  const stopStreaming = () => {
    // 找到正在流式传输的消息
    const streamingMessage = messages.value.find(msg => msg.isStreaming)
    if (streamingMessage) {
      updateMessage(streamingMessage.id, {
        isStreaming: false
      })
    }
    isLoading.value = false
  }

  return {
    // 状态
    messages,
    isLoading,
    currentSessionId,
    error,
    
    // 计算属性
    hasMessages,
    
    // 方法
    sendMessage,
    clearChat,
    loadHistory,
    initSession,
    resendMessage,
    stopStreaming,
    updateMessage
  }
})